var bcrypt = require('bcryptjs');
var shortid = require('shortid');
var moment = require('moment');
var _ = require('lodash');
var logger = require('../common/logger');
var crypto = require('crypto');

moment.locale('zh-cn'); // 使用中文

exports.validateId = function (str) {
  return (/^[a-zA-Z0-9\-_]+$/i).test(str);
};

// 格式化时间
exports.formatDate = function (date, friendly) {
  var _date = moment(date);

  if (friendly) {
    return _date.fromNow();
  }
  return _date.format('YYYY-MM-DD HH:mm');
};

exports.bhash = function (str, callback) {
  if (str) {
    bcrypt.hash(str, 10, callback);
  } else {
    return callback(null, null);
  }
};

exports.bcompare = function (str, hash, callback) {
  bcrypt.compare(str, hash, callback);
};

exports.genPcode = function (callback) {
  // callback(shortid.generate());
  // 简单的纯数字的唯一数算法，安全性上会有问题容易被破解
  var nowtime = (Date.now() - new Date('1987/03/29').getTime() + '').slice(3);
  var rand1 = '', rand2 = '';
  for (var i = 0; i < 3; i++) {
    var r = Math.floor(Math.random() * 10);
    rand1 += r;
  }
  for (var i = 0; i < 3; i++) {
    var r = Math.floor(Math.random() * 10);
    rand2 += r;
  }
  callback(rand1 + nowtime);
};

exports.genAccessToken = function (callback) {
  callback(shortid.generate());
};

exports.checkMissingAttr = function checkMissingAttr(data, attrs) {
  var missings = [];
  _.forEach(attrs, function (attr) {
    if (!_.has(data, attr)) {
      missings.push(attr);
    }
    if (data[attr] === null) {
      missings.push(attr);
    }
  });
  logger.debug(missings);
  missings = _.uniq(missings);
  return missings;
};

//加密
function encrypt(str,secret){
	var cipher = crypto.createCipher('aes192',secret);
	var enc = cipher.update(str,'utf8','hex');
	enc += cipher.final('hex');
	return enc;
}
exports.encrypt = encrypt;
//解密
function decrypt(str,secret){
	var decipher = crypto.createDecipher('aes192',secret);
	// var dec = decipher.update(str,'hex','utf8');
	// dec += decipher.final('utf8');
  // return dec;
  try {
    var dec = decipher.update(str,'hex','utf8');
    dec += decipher.final('utf8');
    return dec;
  } catch (err) {
    console.log(err);
    return;
  }
}
exports.decrypt = decrypt;
